package DMSXL._2024.BinaryTrees;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class averageOfLevels {
    public static void main(String[] args) {
        Integer[] nums = {3,9,20,null,null,15,7};
        TreeNode root = CreateTree.createBinaryTree(nums,0);
        System.out.println(new averageOfLevels().averageOfLevels(root));
    }
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null){
            return result;
        }
        queue.offer(root);
        while (!queue.isEmpty()){
            int n = queue.size();
            double num = 0;
            for (int i = 0; i < n; i++) {
                TreeNode cur = queue.poll();
                num += cur.val;
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            result.add(num / n);
        }
        return result;
    }
}
